// src/main/java/org/example/backend/service/InternshipMaterialService.java
package org.example.backend.service;

import org.example.backend.dto.InternshipMaterialDetailDto;
import org.example.backend.dto.InternshipMaterialDto;
import org.example.backend.entity.*;
import org.example.backend.exception.BusinessException;
import org.example.backend.exception.ResourceNotFoundException;
import org.example.backend.repository.*;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class InternshipMaterialService {

    private final InternshipMaterialRepository internshipMaterialRepository;
    private final InternshipRepository internshipRepository;
    private final InternshipPositionRepository internshipPositionRepository;
    private final CompanyRepository companyRepository;
    private final StudentRepository studentRepository;

    public InternshipMaterialService(InternshipMaterialRepository internshipMaterialRepository,
                                     InternshipRepository internshipRepository,
                                     InternshipPositionRepository internshipPositionRepository,
                                     CompanyRepository companyRepository,
                                     StudentRepository studentRepository) {
        this.internshipMaterialRepository = internshipMaterialRepository;
        this.internshipRepository = internshipRepository;
        this.internshipPositionRepository = internshipPositionRepository;
        this.companyRepository = companyRepository;
        this.studentRepository = studentRepository;
    }

    /**
     * 学生提交实习材料
     */
    public InternshipMaterial submitMaterial(InternshipMaterialDto materialDto, Long studentId) {
        // 检查实习是否存在且属于该学生
        Internship internship = internshipRepository.findById(materialDto.getInternshipId())
                .orElseThrow(() -> new ResourceNotFoundException("实习信息不存在"));

        if (!internship.getStudentId().equals(studentId)) {
            throw new BusinessException("无权限提交该实习的材料");
        }

        // 检查实习状态是否为进行中或已完成
        if (internship.getStatus() != 1 && internship.getStatus() != 2) {
            throw new BusinessException("实习状态不正确，无法提交材料");
        }

        InternshipMaterial material = new InternshipMaterial();
        material.setInternshipId(materialDto.getInternshipId());
        material.setStudentId(studentId);
        material.setType(materialDto.getType());
        material.setTitle(materialDto.getTitle());
        material.setContent(materialDto.getContent());
        material.setFileUrl(materialDto.getFileUrl());
        material.setStatus(0); // 默认待审核状态

        return internshipMaterialRepository.save(material);
    }

    /**
     * 学生更新已提交的实习材料
     */
    public InternshipMaterial updateMaterial(Long materialId, InternshipMaterialDto materialDto, Long studentId) {
        InternshipMaterial material = internshipMaterialRepository.findById(materialId)
                .orElseThrow(() -> new ResourceNotFoundException("实习材料不存在"));

        // 检查材料是否属于该学生
        if (!material.getStudentId().equals(studentId)) {
            throw new BusinessException("无权限操作该材料");
        }

        // 只有待审核状态的材料可以更新
        if (material.getStatus() != 0) {
            throw new BusinessException("该材料状态无法更新");
        }

        material.setType(materialDto.getType());
        material.setTitle(materialDto.getTitle());
        material.setContent(materialDto.getContent());
        material.setFileUrl(materialDto.getFileUrl());

        return internshipMaterialRepository.save(material);
    }

    /**
     * 教师审阅实习材料
     */
    public InternshipMaterial reviewMaterial(Long materialId, Integer status, String rejectReason,
                                             String comment, Long teacherId) {
        InternshipMaterial material = internshipMaterialRepository.findById(materialId)
                .orElseThrow(() -> new ResourceNotFoundException("实习材料不存在"));

        // 检查教师是否有权限审阅该材料（需要是该学生的指导教师）
        Internship internship = internshipRepository.findById(material.getInternshipId())
                .orElseThrow(() -> new ResourceNotFoundException("实习信息不存在"));

        if (!internship.getTeacherId().equals(teacherId)) {
            throw new BusinessException("无权限审阅该材料");
        }

        // 更新材料状态
        material.setStatus(status);
        if (status == 2) { // 拒绝
            material.setRejectReason(rejectReason);
        }
        material.setReviewedAt(new Date());

        // 可以在这里添加评论功能的实现

        return internshipMaterialRepository.save(material);
    }

    /**
     * 获取教师需要审阅的待审核材料
     */
    @Transactional(readOnly = true)
    public Page<InternshipMaterial> getPendingMaterialsByTeacher(Long teacherId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "submittedAt"));
        return internshipMaterialRepository.findByTeacherIdAndStatus(teacherId, 0, pageable);
    }

    /**
     * 学生获取自己提交的材料列表
     */
    @Transactional(readOnly = true)
    public Page<InternshipMaterial> getMaterialsByStudent(Long studentId, Integer type, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "submittedAt"));
        if (type != null) {
            return internshipMaterialRepository.findByStudentIdAndType(studentId, type, pageable);
        }
        return internshipMaterialRepository.findByStudentId(studentId, pageable);
    }

    /**
     * 获取特定实习的所有材料
     */
    @Transactional(readOnly = true)
    public Page<InternshipMaterial> getMaterialsByInternship(Long internshipId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "submittedAt"));
        return internshipMaterialRepository.findByInternshipId(internshipId, pageable);
    }

    /**
     * 获取材料详情
     */
    @Transactional(readOnly = true)
    public InternshipMaterial getMaterialById(Long materialId) {
        return internshipMaterialRepository.findById(materialId)
                .orElseThrow(() -> new ResourceNotFoundException("实习材料不存在"));
    }

    /**
     * 学生删除待审核的材料
     */
    public void deleteMaterial(Long materialId, Long studentId) {
        InternshipMaterial material = internshipMaterialRepository.findById(materialId)
                .orElseThrow(() -> new ResourceNotFoundException("实习材料不存在"));

        // 检查材料是否属于该学生
        if (!material.getStudentId().equals(studentId)) {
            throw new BusinessException("无权限操作该材料");
        }

        // 只有待审核状态的材料可以删除
        if (material.getStatus() != 0) {
            throw new BusinessException("该材料状态无法删除");
        }

        internshipMaterialRepository.deleteById(materialId);
    }

    /**
     * 教师/企业审核实习材料
     */
    public InternshipMaterial reviewMaterial(Long materialId, Long reviewerId, Integer status, String rejectReason) {
        InternshipMaterial material = internshipMaterialRepository.findById(materialId)
                .orElseThrow(() -> new ResourceNotFoundException("实习材料不存在"));

        material.setStatus(status); // 1通过 2拒绝
        if (status == 2) {
            material.setRejectReason(rejectReason);
        }
        material.setReviewedAt(new Date());

        return internshipMaterialRepository.save(material);
    }

    /**
     * 管理员获取所有材料列表
     */
    @Transactional(readOnly = true)
    public Page<InternshipMaterial> getAllMaterials(Integer status, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "submittedAt"));
        return internshipMaterialRepository.findByStatus(status, pageable);
    }

    /**
     * 根据实习ID列表获取所有材料
     */
    @Transactional(readOnly = true)
    public List<InternshipMaterial> getMaterialsByInternshipIds(List<Long> internshipIds) {
        return internshipMaterialRepository.findByInternshipIds(internshipIds);
    }
    // 在 InternshipMaterialService.java 中添加
    @Transactional(readOnly = true)
    public InternshipMaterialDetailDto getMaterialWithDetails(Long materialId) {
        InternshipMaterial material = internshipMaterialRepository.findById(materialId)
                .orElseThrow(() -> new ResourceNotFoundException("实习材料不存在"));

        InternshipMaterialDetailDto dto = new InternshipMaterialDetailDto();
        // 基本信息填充
        dto.setId(material.getId());
        dto.setInternshipId(material.getInternshipId());
        dto.setStudentId(material.getStudentId());
        dto.setType(material.getType());
        dto.setTitle(material.getTitle());
        dto.setContent(material.getContent());
        dto.setFileUrl(material.getFileUrl());
        dto.setStatus(material.getStatus());
        dto.setRejectReason(material.getRejectReason());
        dto.setSubmittedAt(material.getSubmittedAt());
        dto.setReviewedAt(material.getReviewedAt());
        dto.setCreatedAt(material.getCreatedAt());
        dto.setUpdatedAt(material.getUpdatedAt());

        // 获取学生姓名
        try {
            Student student = studentRepository.findById(material.getStudentId())
                    .orElse(null);
            if (student != null) {
                dto.setStudentName(student.getName());
            }
        } catch (Exception e) {
            // 忽略异常
        }

        // 获取实习相关信息
        try {
            Internship internship = internshipRepository.findById(material.getInternshipId())
                    .orElse(null);
            if (internship != null) {
                dto.setInternshipStatus(internship.getStatus());
                dto.setMentorName(internship.getMentorName());

                // 获取公司名称
                Company company = companyRepository.findById(internship.getCompanyId())
                        .orElse(null);
                if (company != null) {
                    dto.setCompanyName(company.getName());
                }

                // 获取岗位名称
                InternshipPosition position = internshipPositionRepository.findById(internship.getPositionId())
                        .orElse(null);
                if (position != null) {
                    dto.setPositionTitle(position.getTitle());
                }
            }
        } catch (Exception e) {
            // 忽略异常
        }

        return dto;
    }

    // 在 InternshipMaterialService.java 中添加
    @Transactional(readOnly = true)
    public Page<InternshipMaterialDetailDto> getMyMaterialsWithDetails(Long studentId, Integer type, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "submittedAt"));
        Page<InternshipMaterial> materials;

        if (type != null) {
            materials = internshipMaterialRepository.findByStudentIdAndType(studentId, type, pageable);
        } else {
            materials = internshipMaterialRepository.findByStudentId(studentId, pageable);
        }

        List<InternshipMaterialDetailDto> dtos = materials.getContent().stream().map(material -> {
            InternshipMaterialDetailDto dto = new InternshipMaterialDetailDto();
            // 基本信息填充
            dto.setId(material.getId());
            dto.setInternshipId(material.getInternshipId());
            dto.setStudentId(material.getStudentId());
            dto.setType(material.getType());
            dto.setTitle(material.getTitle());
            dto.setContent(material.getContent());
            dto.setFileUrl(material.getFileUrl());
            dto.setStatus(material.getStatus());
            dto.setRejectReason(material.getRejectReason());
            dto.setSubmittedAt(material.getSubmittedAt());
            dto.setReviewedAt(material.getReviewedAt());
            dto.setCreatedAt(material.getCreatedAt());
            dto.setUpdatedAt(material.getUpdatedAt());

            // 获取实习相关信息
            try {
                Internship internship = internshipRepository.findById(material.getInternshipId())
                        .orElse(null);
                if (internship != null) {
                    dto.setInternshipStatus(internship.getStatus());
                    dto.setMentorName(internship.getMentorName());

                    // 获取公司名称
                    Company company = companyRepository.findById(internship.getCompanyId())
                            .orElse(null);
                    if (company != null) {
                        dto.setCompanyName(company.getName());
                    }

                    // 获取岗位名称
                    InternshipPosition position = internshipPositionRepository.findById(internship.getPositionId())
                            .orElse(null);
                    if (position != null) {
                        dto.setPositionTitle(position.getTitle());
                    }
                }
            } catch (Exception e) {
                // 忽略异常
            }

            return dto;
        }).collect(Collectors.toList());

        return new PageImpl<>(dtos, pageable, materials.getTotalElements());
    }

    // 在 InternshipMaterialService.java 中添加
    @Transactional(readOnly = true)
    public Page<InternshipMaterialDetailDto> getMaterialsByInternshipWithStudentName(Long internshipId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "submittedAt"));
        Page<InternshipMaterial> materials = internshipMaterialRepository.findByInternshipId(internshipId, pageable);

        List<InternshipMaterialDetailDto> dtos = materials.getContent().stream().map(material -> {
            InternshipMaterialDetailDto dto = new InternshipMaterialDetailDto();
            // 基本信息填充
            dto.setId(material.getId());
            dto.setInternshipId(material.getInternshipId());
            dto.setStudentId(material.getStudentId());
            dto.setType(material.getType());
            dto.setTitle(material.getTitle());
            dto.setContent(material.getContent());
            dto.setFileUrl(material.getFileUrl());
            dto.setStatus(material.getStatus());
            dto.setRejectReason(material.getRejectReason());
            dto.setSubmittedAt(material.getSubmittedAt());
            dto.setReviewedAt(material.getReviewedAt());
            dto.setCreatedAt(material.getCreatedAt());
            dto.setUpdatedAt(material.getUpdatedAt());

            // 获取学生姓名
            try {
                Student student = studentRepository.findById(material.getStudentId())
                        .orElse(null);
                if (student != null) {
                    dto.setStudentName(student.getName());
                }
            } catch (Exception e) {
                // 忽略异常
            }

            // 获取实习相关信息
            try {
                Internship internship = internshipRepository.findById(material.getInternshipId())
                        .orElse(null);
                if (internship != null) {
                    dto.setInternshipStatus(internship.getStatus());
                    dto.setMentorName(internship.getMentorName());

                    // 获取公司名称
                    Company company = companyRepository.findById(internship.getCompanyId())
                            .orElse(null);
                    if (company != null) {
                        dto.setCompanyName(company.getName());
                    }

                    // 获取岗位名称
                    InternshipPosition position = internshipPositionRepository.findById(internship.getPositionId())
                            .orElse(null);
                    if (position != null) {
                        dto.setPositionTitle(position.getTitle());
                    }
                }
            } catch (Exception e) {
                // 忽略异常
            }

            return dto;
        }).collect(Collectors.toList());

        return new PageImpl<>(dtos, pageable, materials.getTotalElements());
    }


}
